<template>
  <div class="merak-upload">
    <div class="merak-upload-content">
      <div v-if="stepActive === 0" class="merak-upload-step-body">
        <el-upload
          action="#"
          accept=".xlsx"
          drag
          :show-file-list="false"
          :before-upload="handleBeforeUpload"
          :http-request="handleRequest"
        >
          <UploadFilled width="80px" height="60px" color="#cfd3dc" />
          <div class="el-upload__text">
            {{ $t("staff_list.upload_drag_here") }} <em>{{ $t("staff_list.upload_by_click") }}</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              {{ $t("goods_important_index.upload_prefix") }}&#44;{{ $t("goods_important_index.upload_suffix") }}&#46;
            </div>
          </template>
        </el-upload>
      </div>
      <div v-if="stepActive === 1" class="merak-upload-progress">
        <span>{{ stepType === 1 ? "文件校验中..." : "文件上传中..." }}</span>
        <el-progress striped striped-flow :percentage="100" :stroke-width="15" :duration="30" :show-text="false" />
      </div>
      <div v-if="stepActive === 2" class="merak-upload-result">
        <el-result :icon="result" :title="resultTitle" :sub-title="errorText">
          <template #extra>
            <el-button type="primary" @click="handleBack">
              {{ $t("merak.back") }}
            </el-button>
          </template>
        </el-result>
      </div>
    </div>
    <el-divider />
    <div class="merak-upload-tip">
      <h5>{{ $t("goods_important_index.tips") }}</h5>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { MerakUploadStepProps } from "./index";

import { getCurrentInstance, ref, computed } from "vue";

import {
  UploadRawFile,
  UploadRequestOptions,
  ElMessage,
  ElSteps,
  ElStep,
  ElUpload,
  ElDivider,
  ElProgress,
  ElResult
} from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";

import { ResultEnum } from "@/enums/httpEnum";
import { uploadStep } from "@/api/modules/upload";

const props = withDefaults(defineProps<MerakUploadStepProps>(), {
  name: "file",
  data: () => ({}),
  params: () => ({})
});

const emit = defineEmits<{
  uploaded: [];
  back: [];
}>();

const currentInstance = getCurrentInstance();

const stepActive = ref(0);

const stepType = ref<0 | 1>(0);

const result = ref<"success" | "info" | "error">("info");

const errorText = ref<string>();

const resultTitle = computed(() => {
  const titles = {
    success: currentInstance?.proxy?.$t("goods_important_index.upload_success"),
    error: currentInstance?.proxy?.$t("goods_important_index.upload_fail")
  };
  return titles[result.value];
});

const handleBeforeUpload = (file: UploadRawFile) => {
  const suffix = file.name.split(".").at(-1);
  const size = Math.floor(file.size / 1024 / 1024);
  if (suffix !== "xlsx") {
    ElMessage.warning(currentInstance?.proxy?.$t("goods_important_index.upload_file_limit"));
    return false;
  }
  if (size >= 1) {
    ElMessage.warning(currentInstance?.proxy?.$t("goods_important_index.upload_size_limit"));
    return false;
  }
};

const handleRequest = async (options: UploadRequestOptions) => {
  const formDate = new FormData();
  formDate.append(props.name, options.file);
  for (let [key, value] of Object.entries(props.data)) {
    if (!!value) {
      formDate.append(key, value);
    }
  }
  stepActive.value = 1;
  stepType.value = 0;
  result.value = "info";
  try {
    await uploadStep(props.path, props.params, formDate, evt => {
      if (evt.percent >= 100) {
        stepType.value = 1;
      }
    })
      .then(({ code, message }) => {
        if (code == ResultEnum.SUCCESS) {
          result.value = "success";
          errorText.value = currentInstance?.proxy?.$t("goods_important_index.import_success");
          emit("uploaded");
        } else {
          result.value = "error";
          if (typeof message === "string") {
            errorText.value = message;
          }
        }
      })
      .catch(() => {
        result.value = "error";
        errorText.value = currentInstance?.proxy?.$t("goods_important_index.server_error");
      });
  } catch {}
  stepActive.value = 2;
};

const handleBack = () => {
  if (result.value === "success") {
    emit("back");
    return;
  }
  stepActive.value = 0;
};
</script>

<style lang="scss">
@import url(./index.scss);
</style>
